package com.zahb.qadx.ui.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseFragmentExt;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.ChoiceExamPublishSuccessActivity;
import com.zahb.qadx.ui.activity.ViewExamDetailsActivity;
import com.zahb.qadx.util.ActivityManager;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.InputMethodUtil;
import com.zahb.qadx.util.JsonUtil;
import com.zahb.qadx.util.Tips;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Zdw on 2020/11/19 17:24
 */
public class CreateChoiceExamFragment2 extends BaseFragmentExt {

    @BindView(R.id.btn_publish_exam)
    AppCompatButton mBtnPublishExam;
    @BindView(R.id.et_exam_name)
    AppCompatEditText mEtExamName;
    @BindView(R.id.tv_total_score)
    AppCompatTextView mTvTotalScore;
    @BindView(R.id.et_pass_proportion)
    AppCompatEditText mEtPassProportion;
    @BindView(R.id.et_exam_duration)
    AppCompatEditText mEtExamDuration;
    @BindView(R.id.tv_exam_term_start)
    AppCompatTextView mTvExamTermStart;
    @BindView(R.id.tv_exam_term_end)
    AppCompatTextView mTvExamTermEnd;
    @BindView(R.id.et_exam_count)
    AppCompatEditText mEtExamCount;
    @BindView(R.id.tv_answer_detail)
    AppCompatTextView mTvAnswerDetail;

    private String mPaperJson;

    private TimePickerView mTermStartPicker, mTermEndPicker;
    private Calendar mStarCalendar, mEndCalendar;
    private final SimpleDateFormat mTimeFormat = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
    private final SimpleDateFormat mDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

    public static CreateChoiceExamFragment2 newInstance(String json, int showMode) {
        Bundle args = new Bundle();
        args.putString("json", json);
        args.putInt("showMode", showMode);// 0不可编辑、提交 1可以编辑提交
        CreateChoiceExamFragment2 fragment = new CreateChoiceExamFragment2();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPaperJson = mArguments.getString("json");
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_create_choice_exam2;
    }

    @Override
    protected void initViews(View rootView) {
        mUnbinder = ButterKnife.bind(this, rootView);

        int showMode = mArguments.getInt("showMode");
        if (showMode == 0) {
            mBtnPublishExam.setVisibility(View.VISIBLE);
            mBtnPublishExam.setText("关闭");
            mBtnPublishExam.setOnClickListener(v -> {
                if (getActivity() instanceof ViewExamDetailsActivity) {
                    getActivity().finish();
                }
            });

            JsonObject jsonObject = JsonParser.parseString(mArguments.getString("json", "")).getAsJsonObject();
            mEtExamName.setText(jsonObject.get("examName").getAsString());
            mEtExamName.setEnabled(false);
            mTvTotalScore.setText(String.valueOf((int) jsonObject.get("totalScore").getAsDouble()));
            mTvTotalScore.setEnabled(false);
            mEtPassProportion.setText(String.valueOf((int) jsonObject.get("passScore").getAsDouble()));
            mEtPassProportion.setEnabled(false);
            mEtExamDuration.setText(String.valueOf((int) jsonObject.get("examTime").getAsDouble()));
            mEtExamDuration.setEnabled(false);
            mTvExamTermStart.setText(jsonObject.get("startTime").getAsString());
            mTvExamTermStart.setEnabled(false);
            mTvExamTermEnd.setText(jsonObject.get("endTime").getAsString());
            mTvExamTermEnd.setEnabled(false);
            int limitTimes = (int) jsonObject.get("limitTimes").getAsDouble();
            if (limitTimes > 0)
                mEtExamCount.setText(String.valueOf(limitTimes));
            else
                mEtExamCount.setText("不限制");
            mEtExamCount.setEnabled(false);
        } else if (showMode == 1) {
            mBtnPublishExam.setVisibility(View.VISIBLE);

            JsonObject jsonObject = JsonParser.parseString(mPaperJson).getAsJsonObject();
            mEtExamName.setText(jsonObject.get("paperName").getAsString());
            int totalScore = jsonObject.get("totalScore").getAsInt();
            mTvTotalScore.setText(String.valueOf(totalScore));
            int passScore = jsonObject.get("passScore").getAsInt();
            mEtPassProportion.setText(String.valueOf(passScore));
            mEtExamCount.setText(String.valueOf(1));

            mStarCalendar = Calendar.getInstance();
            mStarCalendar.set(Calendar.HOUR_OF_DAY, mStarCalendar.getActualMinimum(Calendar.HOUR_OF_DAY));
            mStarCalendar.set(Calendar.MINUTE, mStarCalendar.getActualMinimum(Calendar.MINUTE));
            mStarCalendar.set(Calendar.SECOND, mStarCalendar.getActualMinimum(Calendar.SECOND));
            mTvExamTermStart.setText(mTimeFormat.format(mStarCalendar.getTime()));
            mEndCalendar = Calendar.getInstance();
            mEndCalendar.set(Calendar.HOUR_OF_DAY, mStarCalendar.getActualMaximum(Calendar.HOUR_OF_DAY));
            mEndCalendar.set(Calendar.MINUTE, mStarCalendar.getActualMaximum(Calendar.MINUTE));
            mEndCalendar.set(Calendar.SECOND, mStarCalendar.getActualMaximum(Calendar.SECOND));
            mTvExamTermEnd.setText(mTimeFormat.format(mEndCalendar.getTime()));
        }
    }

    @OnClick({R.id.btn_publish_exam, R.id.tv_exam_term_start, R.id.tv_exam_term_end})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_publish_exam: {
                if (checkPrepared()) {
                    opreationExamination();
                }
            }
            break;
            case R.id.tv_exam_term_start: {
                InputMethodUtil.hideInputMethod(getActivity());
                if (mTermStartPicker == null) {
                    mTermStartPicker = new TimePickerBuilder(getContext(), (date, v) -> {
                        mStarCalendar.setTime(date);
                        mTvExamTermStart.setText(mTimeFormat.format(date));
                    }).setType(new boolean[]{false, false, false, true, true, true})
                            .setTitleText("开始时间")
                            .build();
                    mTermStartPicker.setDate(mStarCalendar);
                }
                mTermStartPicker.show();
            }
            break;
            case R.id.tv_exam_term_end: {
                InputMethodUtil.hideInputMethod(getActivity());
                if (mTermEndPicker == null) {
                    mTermEndPicker = new TimePickerBuilder(getContext(), (date, v) -> {
                        mEndCalendar.setTime(date);
                        mTvExamTermEnd.setText(mTimeFormat.format(date));
                    }).setType(new boolean[]{false, false, false, true, true, true})
                            .setTitleText("结束时间")
                            .build();
                    mTermEndPicker.setDate(mEndCalendar);
                }
                mTermEndPicker.show();
            }
            break;
        }
    }

    private boolean checkPrepared() {
        if (CompatHelper.isEmpty(mEtExamName)) {
            showBindToast("请输入考试名称");
            return false;
        }
        if (CompatHelper.isEmpty(mEtPassProportion)) {
            showBindToast("请输入及格比例");
            return false;
        }
        int passProportion = Integer.parseInt(CompatHelper.getString(mEtPassProportion));
        if (passProportion >= 100) {
            showBindToast("及格比例不能大于100");
            return false;
        }
        if (CompatHelper.isEmpty(mEtExamDuration)) {
            showBindToast("请输入考试时长");
            return false;
        }
        int examDuration = Integer.parseInt(CompatHelper.getString(mEtExamDuration));
        if (examDuration == 0) {
            showBindToast("考试时长不能为0");
            return false;
        }
        if (CompatHelper.isEmpty(mEtExamCount)) {
            showBindToast("请输入考试次数");
            return false;
        }
        return true;
    }

    private void opreationExamination() {
        showProgressDialog("请稍等...");
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), mPaperJson);
        addDisposable(RetrofitService.getNetService()
                .opreationExamination(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        saveAndPublishChoiceExam(response.getData());
                    } else {
                        hideProgressDialog();
                        if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                            showBindToast(response.getErrorInfo());
                        }
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    private void saveAndPublishChoiceExam(int examPaperId) {
        JsonObject jsonObject = JsonParser.parseString(mPaperJson).getAsJsonObject();
        Map<String, Object> params = new TreeMap<>();
        params.put("cheatType", 0);// 防作弊设置 0 不限 1 防切屏 2 人脸
        params.put("startTime", mDateTimeFormat.format(mStarCalendar.getTime()));
        params.put("endTime", mDateTimeFormat.format(mEndCalendar.getTime()));
        params.put("examName", CompatHelper.getString(mEtExamName));
        params.put("examPaperId", examPaperId);
        params.put("examPaperName", jsonObject.get("paperName").getAsString());
        params.put("examTime", Integer.parseInt(CompatHelper.getString(mEtExamDuration)));
        params.put("examType", 2);// 考试类型 0 线上 1 线下 2 抽考
        params.put("isForce", 0);// 是否强制交卷 0 否 1 是
        params.put("isPublish", 1);// 是否发布 0 未发布 1 已发布
        params.put("limitCheck", 2);// 查看权限 0 不可查看 1 仅可看对错 2 可看对错和解析
        params.put("limitTimes", Integer.parseInt(CompatHelper.getString(mEtExamCount)));
        params.put("passScore", Integer.parseInt(CompatHelper.getString(mEtPassProportion)));
        params.put("totalScore", jsonObject.get("totalScore").getAsInt());

        addDisposable(RetrofitService.getNetService()
                .saveAndPublishChoiceExam(JsonUtil.getRequestBody(params))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        ChoiceExamPublishSuccessActivity.actionStart(
                                getContext(), response.getData(), ((String) params.get("examName")),
                                ((String) params.get("startTime")), ((String) params.get("endTime")));
                        ActivityManager.getInstance().finishActivities(ActivityManager.KEY_CREATE_CHOICE_EXAM);
                    } else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }
}
